<template>
  <div class="home-container" v-loading="loading">
    <!-- 管理员信息 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="hover" class="admin-info-card">
          <div class="admin-info">
            <div class="avatar-container">
              <el-avatar :size="80" icon="el-icon-user-solid"></el-avatar>
            </div>
            <div class="info-container">
              <h2>{{ userInfo.username || '管理员' }}</h2>
              <p>权限等级：{{ userRoleText }}</p>
              <p>上次登录时间：{{ formatDate(userInfo.lastLoginTime) }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="card-header">
              <span>未发货订单</span>
              <el-tag size="small" effect="dark" type="warning">待处理</el-tag>
            </div>
          </template>
          <div class="card-value">{{ formatNumber(overview.pendingOrders || 0) }}</div>
          <div class="card-footer">
            <el-button type="primary" size="small" @click="goToOrders">查看订单</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="card-header">
              <span>今日销售额</span>
              <el-tag size="small" effect="dark" type="success">今日</el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ formatNumber(overview.todaySales || 0) }}</div>
          <div class="card-footer">
            <span class="trend-info" v-if="userStore.canViewDetailedStats">
              <i class="el-icon-top" style="color: #67C23A;"></i>
              较昨日增长 {{ dailyGrowth }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="card-header">
              <span>最高销售额产品</span>
              <el-tag size="small" effect="dark" type="primary">热销</el-tag>
            </div>
          </template>
          <div class="card-product">
            <h3>{{ overview.topProduct?.name || '暂无数据' }}</h3>
            <div class="card-value">¥{{ formatNumber(overview.topProduct?.sales || 0) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 - 仅管理员和超级管理员可见 -->
    <div v-if="userStore.canViewDetailedStats">
      <el-row :gutter="20" class="mb-4">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>产品销售曲线</span>
                <el-radio-group v-model="timeRange" size="small">
                  <el-radio-button value="week">本周</el-radio-button>
                  <el-radio-button value="month">本月</el-radio-button>
                  <el-radio-button value="year">全年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" v-loading="chartLoading">
              <div ref="salesTrendChartRef" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>分类销售变化</span>
              </div>
            </template>
            <div class="chart-container" v-loading="chartLoading">
              <div ref="categorySalesChartRef" class="chart"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>分类销售占比</span>
              </div>
            </template>
            <div class="chart-container" v-loading="chartLoading">
              <div ref="categoryPercentageChartRef" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 普通用户专属内容 -->
    <div v-if="userStore.isUser" class="mb-4">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
          </div>
        </template>
        <div class="user-info-content">
          <p>欢迎使用商城管理系统，您当前的权限为普通用户。</p>
          <p>您可以查看基本的销售数据和订单信息，但无法查看详细的统计图表和执行管理操作。</p>
          <p>如需更多权限，请联系系统管理员。</p>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getOverview, getSalesTrend, getCategorySales, getSalesPercentage } from '@/api/dashboard'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const chartLoading = ref(false)
const timeRange = ref('month')

// 图表DOM引用
const salesTrendChartRef = ref(null)
const categorySalesChartRef = ref(null)
const categoryPercentageChartRef = ref(null)

// 图表实例
const salesTrendChart = ref(null)
const categorySalesChart = ref(null)
const categoryPercentageChart = ref(null)

// 用户信息
const userInfo = reactive({
  username: '',
  role: '',
  lastLoginTime: new Date()
})

// 用户角色文本
const userRoleText = computed(() => {
  switch (userStore.role) {
    case 'SUPER_ADMIN':
      return '超级管理员';
    case 'ADMIN':
      return '管理员';
    case 'USER':
      return '普通用户';
    default:
      return '未知角色';
  }
})

// 概览数据
const overview = reactive({
  pendingOrders: 0,
  todaySales: 0,
  totalSales: 0,
  totalOrders: 0,
  totalUsers: 0,
  totalProducts: 0,
  topProduct: {
    name: '',
    sales: 0
  }
})

// 图表数据
const salesTrend = ref([])
const categorySales = ref([])
const salesPercentage = ref([])
const dailyGrowth = ref(5.2) // 示例数据，实际应从API获取

// 格式化数字
const formatNumber = (num) => {
  if (typeof num !== 'number') return '0.00'
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无数据'
  if (typeof date === 'string') {
    date = new Date(date)
  }
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 跳转到订单页面
const goToOrders = () => {
  router.push('/orders')
}

// 初始化图表
const initCharts = () => {
  // 如果用户没有查看详细统计的权限，则不初始化图表
  if (!userStore.canViewDetailedStats) {
    console.log('User does not have permission to view detailed stats, skipping chart initialization')
    return
  }

  try {
    console.log('Initializing charts...')
    
    // 销售趋势图表
    if (salesTrendChartRef.value) {
      try {
        salesTrendChart.value = echarts.init(salesTrendChartRef.value)
        console.log('Sales trend chart initialized')
      } catch (error) {
        console.error('Failed to initialize sales trend chart:', error)
        salesTrendChart.value = null
      }
    }
    
    // 分类销售图表
    if (categorySalesChartRef.value) {
      try {
        categorySalesChart.value = echarts.init(categorySalesChartRef.value)
        console.log('Category sales chart initialized')
      } catch (error) {
        console.error('Failed to initialize category sales chart:', error)
        categorySalesChart.value = null
      }
    }
    
    // 销售占比图表
    if (categoryPercentageChartRef.value) {
      try {
        categoryPercentageChart.value = echarts.init(categoryPercentageChartRef.value)
        console.log('Category percentage chart initialized')
      } catch (error) {
        console.error('Failed to initialize category percentage chart:', error)
        categoryPercentageChart.value = null
      }
    }
    
    // 更新图表数据
    updateCharts()
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('Chart initialization error:', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  try {
    if (salesTrendChart.value) {
      salesTrendChart.value.resize()
    }
    if (categorySalesChart.value) {
      categorySalesChart.value.resize()
    }
    if (categoryPercentageChart.value) {
      categoryPercentageChart.value.resize()
    }
  } catch (error) {
    console.error('Chart resize error:', error)
  }
}

// 更新所有图表
const updateCharts = () => {
  try {
    updateSalesTrendChart()
    updateCategorySalesChart()
    updateCategoryPercentageChart()
  } catch (error) {
    console.error('Update charts error:', error)
  }
}

// 更新销售趋势图表
const updateSalesTrendChart = () => {
  if (!salesTrendChart.value) {
    console.log('Sales trend chart not initialized, skipping update')
    return
  }
  
  try {
    const option = {
      title: {
        text: '产品销售趋势'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: salesTrend.value.length > 0 
          ? salesTrend.value.map(item => item.date) 
          : ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      series: [
        {
          name: '销售额',
          type: 'line',
          data: salesTrend.value.length > 0 
            ? salesTrend.value.map(item => item.sales) 
            : [5000, 8000, 12000, 9000, 15000, 20000],
          smooth: true,
          areaStyle: {
            opacity: 0.2
          },
          lineStyle: {
            width: 3
          },
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }
    
    salesTrendChart.value.setOption(option)
  } catch (error) {
    console.error('Update sales trend chart error:', error)
  }
}

// 更新分类销售图表
const updateCategorySalesChart = () => {
  if (!categorySalesChart.value) return
  
  try {
    const option = {
      title: {
        text: '分类销售变化'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: categorySales.value.length > 0 
          ? categorySales.value.map(item => item.category) 
          : ['电子产品', '服装', '食品', '家居']
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      series: categorySales.value.length > 0 
        ? categorySales.value.map(item => ({
            name: item.category,
            type: 'bar',
            data: item.data
          }))
        : [
            {
              name: '电子产品',
              type: 'bar',
              data: [5000, 8000, 12000, 9000, 15000, 20000, 18000, 22000, 19000, 25000, 28000, 30000]
            },
            {
              name: '服装',
              type: 'bar',
              data: [3000, 4000, 6000, 5000, 7000, 9000, 8000, 10000, 9500, 11000, 12000, 15000]
            }
          ]
    }
    
    categorySalesChart.value.setOption(option)
  } catch (error) {
    console.error('Update category sales chart error:', error)
  }
}

// 更新销售占比图表
const updateCategoryPercentageChart = () => {
  if (!categoryPercentageChart.value) return
  
  try {
    const option = {
      title: {
        text: '分类销售占比'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: salesPercentage.value.length > 0 
          ? salesPercentage.value.map(item => item.category) 
          : ['电子产品', '服装', '食品', '家居', '其他']
      },
      series: [
        {
          name: '销售占比',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: salesPercentage.value.length > 0 
            ? salesPercentage.value.map(item => ({
                name: item.category,
                value: item.value
              }))
            : [
                { name: '电子产品', value: 45 },
                { name: '服装', value: 25 },
                { name: '食品', value: 15 },
                { name: '家居', value: 10 },
                { name: '其他', value: 5 }
              ]
        }
      ]
    }
    
    categoryPercentageChart.value.setOption(option)
  } catch (error) {
    console.error('Update category percentage chart error:', error)
  }
}

// 获取首页数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    // 获取用户信息
    userInfo.username = userStore.username
    userInfo.role = userStore.role
    userInfo.lastLoginTime = userStore.lastLoginTime || new Date()
    
    // 获取概览数据
    try {
      const overviewRes = await getOverview()
      if (overviewRes.code === 200 && overviewRes.data) {
        overview.pendingOrders = overviewRes.data.pendingOrders || 0
        overview.todaySales = overviewRes.data.todaySales || 0
        overview.totalSales = overviewRes.data.totalSales || 0
        overview.totalOrders = overviewRes.data.totalOrders || 0
        overview.totalUsers = overviewRes.data.totalUsers || 0
        overview.totalProducts = overviewRes.data.totalProducts || 0
        
        if (overviewRes.data.topProduct) {
          overview.topProduct = overviewRes.data.topProduct
        }
      }
    } catch (error) {
      console.error('获取概览数据失败:', error)
      ElMessage.error('获取概览数据失败')
    }
    
    // 只有管理员和超级管理员才获取图表数据
    if (userStore.canViewDetailedStats) {
      await fetchChartData()
    }
  } catch (error) {
    console.error('获取首页数据失败:', error)
    ElMessage.error('获取首页数据失败')
  } finally {
    loading.value = false
  }
}

// 获取图表数据
const fetchChartData = async () => {
  chartLoading.value = true
  try {
    // 获取销售趋势数据
    try {
      const trendRes = await getSalesTrend()
      if (trendRes.code === 200 && trendRes.data) {
        const { months, values } = trendRes.data
        salesTrend.value = months.map((month, index) => ({
          date: month,
          sales: values[index]
        }))
      }
    } catch (error) {
      console.error('获取销售趋势数据失败:', error)
    }
    
    // 获取分类销售数据
    try {
      const categorySalesRes = await getCategorySales()
      if (categorySalesRes.code === 200 && categorySalesRes.data) {
        const { values } = categorySalesRes.data
        categorySales.value = Object.keys(values).map(category => ({
          category,
          data: values[category]
        }))
      }
    } catch (error) {
      console.error('获取分类销售数据失败:', error)
    }
    
    // 获取销售占比数据
    try {
      const percentageRes = await getSalesPercentage()
      if (percentageRes.code === 200 && percentageRes.data) {
        const { categories, percentages } = percentageRes.data
        salesPercentage.value = categories.map((category, index) => ({
          category,
          value: percentages[index]
        }))
      }
    } catch (error) {
      console.error('获取销售占比数据失败:', error)
    }
    
    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取图表数据失败')
  } finally {
    chartLoading.value = false
  }
}

// 监听时间范围变化
watch(timeRange, () => {
  fetchChartData()
})

onMounted(() => {
  console.log('Dashboard component mounted')
  
  // 获取数据
  fetchDashboardData()
  
  // 初始化图表，延迟确保DOM已渲染
  setTimeout(() => {
    initCharts()
  }, 500)
})

onBeforeUnmount(() => {
  console.log('Dashboard component unmounting')
  
  try {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', handleResize)
    
    // 销毁图表实例
    if (salesTrendChart.value) {
      try {
        salesTrendChart.value.dispose()
      } catch (e) {
        console.error('Error disposing sales trend chart:', e)
      }
      salesTrendChart.value = null
    }
    
    if (categorySalesChart.value) {
      try {
        categorySalesChart.value.dispose()
      } catch (e) {
        console.error('Error disposing category sales chart:', e)
      }
      categorySalesChart.value = null
    }
    
    if (categoryPercentageChart.value) {
      try {
        categoryPercentageChart.value.dispose()
      } catch (e) {
        console.error('Error disposing category percentage chart:', e)
      }
      categoryPercentageChart.value = null
    }
    
    console.log('All charts disposed')
  } catch (error) {
    console.error('Error in onBeforeUnmount:', error)
  }
})
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}

.admin-info-card {
  .admin-info {
    display: flex;
    align-items: center;
    
    .avatar-container {
      margin-right: 20px;
    }
    
    .info-container {
      h2 {
        margin-top: 0;
        margin-bottom: 10px;
        font-size: 20px;
      }
      
      p {
        margin: 5px 0;
        color: #666;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin: 10px 0;
}

.card-footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-product {
  h3 {
    margin-top: 0;
    margin-bottom: 10px;
  }
}

.trend-info {
  font-size: 14px;
  color: #67C23A;
}

.chart-container {
  height: 400px;
  position: relative;
  
  .chart {
    width: 100%;
    height: 100%;
  }
}

.user-info-content {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  
  p {
    margin: 10px 0;
    line-height: 1.6;
  }
}
</style> 